package com.example.utils;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;
@Configuration
@Slf4j
public class CommonControllers {

    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 文件上传工具类
     * @param file
     * @return
     */

    @ApiOperation("文件上传")
    public String upload(MultipartFile file){
        log.info("文件上传：{}",file);
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀   dfdfdf.png
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName = UUID.randomUUID().toString() + extension;
            System.out.println(objectName);
            //文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);

            return filePath;

        } catch (IOException e) {
            log.error("文件上传失败：{}", e);
        }

        return "文件上传失败";
    }

    /**
     * 删除文件
     * @param ScriptFile
     * @return
     */
    @ApiOperation("删除文件")
    public String delete(String ScriptFile){
        log.info("删除文件：{}",ScriptFile);
        String objectName = ScriptFile.substring(ScriptFile.lastIndexOf("/")+1);
        boolean delete = aliOssUtil.delete(objectName);
        System.out.println(delete);
        return "删除成功";
    }
}
